package com.spzx.product.utils;

import com.spzx.product.api.domain.vo.CategoryVo;

import java.util.ArrayList;
import java.util.List;

public class CategoryUtils {

    public static List<CategoryVo> buildTree(List<CategoryVo> categoryVoList) {
        List<CategoryVo> treeList = new ArrayList<>();
        for (CategoryVo categoryVo : categoryVoList) {
            if (categoryVo.getParentId() == 0) {
                treeList.add(findChildren(categoryVo, categoryVoList));
            }
        }
        return treeList;
    }

    private static CategoryVo findChildren(CategoryVo categoryVo, List<CategoryVo> categoryVoList) {
       categoryVo.setChildren(new ArrayList<>());
       for (CategoryVo child : categoryVoList) {
           if (child.getParentId().longValue() == categoryVo.getId().longValue()) {
               if(categoryVo.getChildren()==null){
                   categoryVo.setChildren(new ArrayList<>());
               }
               categoryVo.getChildren().add(findChildren(child, categoryVoList));
           }
       }
       return categoryVo;
    }
}